package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import build_util.APITestLegacy;

import com.ebay.ice.api.ResultObj;
import com.ebay.ice.api.TaskDetailObj;

import env.GlobalEnv;

public class BuildHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BuildHandler() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		String creator = null;

		String locale = null;
		String requestType = null;
		String featureOrTrackerID = null;
		String poolType = null;
		String buildType = null;
		String projectName = null;
		String deliverable = null;
		String configSpec = null;
		String loadRules = null;
//		String taskParam = null;
		boolean autoDeploy = false;

		creator = request.getParameter("creator");
		System.out.println("Creator is " + creator);
		GlobalEnv.setCreator(creator);

		int projectNum = Integer.parseInt(request.getParameter("projectNum"));
		System.out.println("Project num is " + projectNum);

		APITestLegacy tb = null;
		ResultObj result = null;

		for (int i = 1; i <= projectNum; i++) {

			locale = request.getParameter("locale-" + i);
			requestType = request.getParameter("requestType-" + i);
			featureOrTrackerID = request
					.getParameter("featureOrTrackerID-" + i);
			poolType = request.getParameter("poolType-" + i);
			buildType = request.getParameter("buildType-" + i);
			projectName = request.getParameter("projectName-" + i);
			deliverable = request.getParameter("deliverable-" + i);
			configSpec = request.getParameter("configSpec-" + i);
			loadRules = request.getParameter("loadRules-" + i);
//			taskParam = request.getParameter("taskParam-" + i);
			autoDeploy = request.getParameter("autoDeploy-" + i) == null ? false
					: true;

			if (creator == null || "".equals(creator.trim()) || locale == null
					|| requestType == null || featureOrTrackerID == null
					|| poolType == null || buildType == null
					|| projectName == null || "".equals(projectName.trim())
					|| deliverable == null || configSpec == null
					|| loadRules == null) {
				out.println("Build failed, for build params are illegal! Please check if yourself!");
				out.flush();
				out.close();

				return;
			}
//			taskParam = taskParam == null ? "" : taskParam;
			
			System.out.println("Request type: " + requestType);
			System.out.println("Pool type: " + poolType);
			System.out.println("Feature or Tracker ID:" + featureOrTrackerID);

			tb = new APITestLegacy();
			// ----------- Step1: Create a Request
			// --------------------------------------
			result = tb.createRequest(Integer.parseInt(requestType),
					Integer.parseInt(poolType),
					Integer.parseInt(featureOrTrackerID), null);

			if (result.getResultId() <= 0) {
				System.out
						.println("Failed to create request!\r\nMessage if any\r\n"
								+ result.getError());
				return;
			} else {
				System.out.println("Request created, result id is: " + result.getResultId());
			}
			
			/*
		TaskDetailObj[] tasks = new TaskDetailObj[4];
        tasks[0] = new TaskDetailObj();
        tasks[1] = new TaskDetailObj();
        tasks[2] = new TaskDetailObj();
        tasks[3] = new TaskDetailObj();

        tasks[0].setName("ViewSync");
        tasks[0].setParameter("");
        
        tasks[1].setName("CCCreate");
        tasks[1].setParameter("-nomegajar -dynamic");

        tasks[2].setName("BuildV3Library");
        tasks[2].setParameter("-keepoutput -gencheckin -runbuild3 -buildupgradejdk -deliverable Kernel -deliverable uKernel -deliverable uKernelCore -clean -antarg -Dglobal.run.tests=false -noofinstances 12");
    
        tasks[3].setName("CheckInV3Library");
        tasks[3].setParameter("");

        result = tb.addProject("API Kernallibrary Build", ConstDef.BUILDTYPE_KernalLibrary, reqID, configSpec, loadRules, tasks,ConstDef.LOCALE_CORE,false);
			 */

			// -noclean -keepoutput -gencheckin -runbuild3
			TaskDetailObj[] tasks = new TaskDetailObj[4];
			tasks[0] = new TaskDetailObj();
			tasks[1] = new TaskDetailObj();
			tasks[2] = new TaskDetailObj();
			tasks[3] = new TaskDetailObj();

			tasks[0].setName("ViewSync");
			tasks[0].setParameter("");

			tasks[1].setName("CCCreate");
			tasks[1].setParameter("-nomegajar -ParallelCCCreateThreadCount 14");

			tasks[2].setName("BuildV3Library");
			tasks[2].setParameter("-noclean -keepoutput -gencheckin -runbuild3 -deliverable " + deliverable + " -noofinstances 10");

			tasks[3].setName("CheckInV3Library");
			tasks[3].setParameter("");

			// ------------ Step2: Add a project a given request
			// -------------------------
			int reqID = result.getResultId();
			
			/*
			System.out.println("---------------------------------");
			System.out.println("Build parameters as follow: ");
			System.out.println("Locales is: " + locale);
			System.out.println("Build type: " + buildType);
			System.out.println("Request ID: " + reqID);
			System.out.println("---------------------------------");
			*/
			
			result = tb.addProject(projectName, Integer.parseInt(buildType),
					reqID, configSpec, loadRules, tasks,
					Integer.parseInt(locale), autoDeploy);
			
			if (!result.isSuccess()) {
				System.out.println("Failed to add project to request!");
				System.exit(1);
			} else {
				System.out.println("Project (id =  " + result.getResultId()
						+ ") is created for request (id = " + reqID + ")");
			}

			// ------------ Step3: Start a Build
			// ----------------------------------------------
			result = tb.activate(reqID);
			int rbgID = -1;
			if (result.isSuccess()) {
				// Get the request build group id if activated successfully
				rbgID = result.getResultId();
			} else {
				out.println("Failed to start the build for build group "
						+ rbgID);
				out.flush();
				out.close();
				return;
			}
			
			// redirect to ice corp web site to check build status
			RequestDispatcher dispatcher = request.getRequestDispatcher("redirect_to_ice.html");
			dispatcher.forward(request, response);
		}

	}
}